package dk.dashboardFP.utils.WordListener {
	import flash.display.Stage;
	import flash.events.EventDispatcher;
	import flash.events.KeyboardEvent;

	/**
	 * @author josef
	 */
	public class WordListener extends EventDispatcher {

		private static var _oInstance : WordListener;
		private static var _bCreatingInstance : Boolean = false;
		private var _oStage : Stage;
		private var _sCollectedString : String = "";
		private var _bCheckOnEveryEntry : Boolean = false;
		private var _a_oHitWords : Array;
		private var _bInitDone : Boolean=false;

		public function WordListener() {
			if( !_bCreatingInstance ) throw new Error("Singleton and can only be accessed through WordListener.get_oInstance()");
		}

		public function initWordListener(oStage : Stage) : void {
			
			if (!_bInitDone) {
				
				_oStage = oStage;
				setupListener();
				
				_bInitDone=true;
			}
		}

		public function addHitWord(sHitWord:String, fCallback:Function) : void {
			_a_oHitWords.push(new HitWord(sHitWord, fCallback));
		}

		private function setupListener() : void {
			
			//:::::::
			// hit words 
			_a_oHitWords = new Array();
			
			//:::::::
			// lisetener 
			_oStage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown, false, 0, true);
		}

		private function onKeyDown(event : KeyboardEvent) : void {
			
			if (event.charCode != 13) {
				_sCollectedString += String.fromCharCode(event.charCode);
			}
			
			if (_bCheckOnEveryEntry) {
				hitCheck();
			}
			
			if (event.charCode == 13) {
				hitCheck();
				resetCollectedString();
			}
		}

		private function resetCollectedString() : void {
			_sCollectedString = "";
		}

		private function hitCheck() : Boolean {
			
			var bHitSucces : Boolean = false;
			
			for each (var i : HitWord in _a_oHitWords) {
				
				if (i.sWord.toLowerCase().toString() == _sCollectedString.toLowerCase().toString()) {
					
					i.fCallback();
					bHitSucces = true;
				}
			}
			
			return bHitSucces;
		}

		public static function getInstance() : WordListener {
			if (!_oInstance) {
				_bCreatingInstance = true;
				_oInstance = new WordListener();
				_bCreatingInstance = false;
			}
			return _oInstance;
		}
	}
}
